<template>
  <div class="pricing-page">
    <div class="page-header">
      <h2>
        <el-icon><Money /></el-icon>
        商品价格管理
      </h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleBatchPricing">
          <el-icon><Edit /></el-icon>
          批量调价
        </el-button>
        <el-button type="success" @click="handlePricingStrategy">
          <el-icon><Setting /></el-icon>
          定价策略
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：商品价格列表 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>商品价格列表</span>
              <el-input
                v-model="searchText"
                placeholder="搜索商品..."
                clearable
                style="width: 300px"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </template>

          <el-table :data="filteredProducts" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="code" label="商品编码" width="120" />
            <el-table-column prop="name" label="商品名称" min-width="150" />
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column label="采购价" width="120">
              <template #default="{ row }">
                <div class="price-cell">
                  <span>¥{{ row.purchasePrice }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="销售价" width="120">
              <template #default="{ row }">
                <div class="price-cell">
                  <span>¥{{ row.salePrice }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="毛利率" width="100">
              <template #default="{ row }">
                <el-tag :type="getProfitType(row.profitMargin)">
                  {{ row.profitMargin }}%
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastPriceChange" label="最后调价" width="160" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" text @click="handleAdjustPrice(row)">
                  调价
                </el-button>
                <el-button type="success" size="small" text @click="handlePriceHistory(row)">
                  历史
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧：调价记录 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>最近调价记录</span>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="record in priceRecords"
              :key="record.id"
              :timestamp="record.time"
              size="small"
            >
              <div class="record-content">
                <div class="record-header">
                  <strong>{{ record.productName }}</strong>
                  <el-tag :type="record.type === '涨价' ? 'danger' : 'success'" size="small">
                    {{ record.type }}
                  </el-tag>
                </div>
                <div class="record-detail">
                  <span class="old-price">¥{{ record.oldPrice }}</span>
                  <el-icon><Right /></el-icon>
                  <span class="new-price">¥{{ record.newPrice }}</span>
                </div>
                <div class="record-reason">原因：{{ record.reason }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 调价对话框 -->
    <el-dialog v-model="priceDialogVisible" title="商品调价" width="600px">
      <el-form :model="priceForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="currentProduct.name" disabled />
        </el-form-item>
        
        <el-divider>采购价调整</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当前采购价">
              <el-input v-model="currentProduct.purchasePrice" disabled>
                <template #prepend>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新采购价">
              <el-input-number
                v-model="priceForm.newPurchasePrice"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>销售价调整</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当前销售价">
              <el-input v-model="currentProduct.salePrice" disabled>
                <template #prepend>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新销售价">
              <el-input-number
                v-model="priceForm.newSalePrice"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="调价方式">
          <el-radio-group v-model="priceForm.adjustType">
            <el-radio label="fixed">固定金额</el-radio>
            <el-radio label="percentage">百分比</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="调价幅度" v-if="priceForm.adjustType === 'percentage'">
          <el-input-number v-model="priceForm.adjustPercentage" :min="-100" :max="100" style="width: 200px">
            <template #append>%</template>
          </el-input-number>
          <el-button type="primary" size="small" @click="applyPercentage" style="margin-left: 10px">
            应用
          </el-button>
        </el-form-item>

        <el-form-item label="生效时间">
          <el-date-picker
            v-model="priceForm.effectiveTime"
            type="datetime"
            placeholder="选择生效时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="调价原因">
          <el-select v-model="priceForm.reason" placeholder="请选择" style="width: 100%">
            <el-option label="成本上涨" value="成本上涨" />
            <el-option label="市场调整" value="市场调整" />
            <el-option label="促销活动" value="促销活动" />
            <el-option label="竞争对手调价" value="竞争对手调价" />
            <el-option label="季节性调整" value="季节性调整" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注说明">
          <el-input v-model="priceForm.remark" type="textarea" :rows="3" />
        </el-form-item>

        <el-alert
          v-if="priceChangeInfo"
          :title="priceChangeInfo"
          type="info"
          :closable="false"
          style="margin-top: 10px"
        />
      </el-form>

      <template #footer>
        <el-button @click="priceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPrice">确认调价</el-button>
      </template>
    </el-dialog>

    <!-- 定价策略对话框 -->
    <el-dialog v-model="strategyDialogVisible" title="定价策略" width="700px">
      <el-tabs v-model="strategyTab">
        <el-tab-pane label="加价率策略" name="markup">
          <el-form label-width="120px">
            <el-form-item label="默认加价率">
              <el-input-number v-model="strategy.defaultMarkup" :min="0" :precision="1" style="width: 200px">
                <template #append>%</template>
              </el-input-number>
              <span style="margin-left: 10px; color: #909399">销售价 = 采购价 × (1 + 加价率)</span>
            </el-form-item>

            <el-divider>分类加价率</el-divider>
            <el-table :data="strategy.categoryMarkups" stripe>
              <el-table-column prop="category" label="商品分类" />
              <el-table-column label="加价率">
                <template #default="{ row }">
                  <el-input-number v-model="row.markup" :min="0" :precision="1" size="small">
                    <template #append>%</template>
                  </el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="会员价策略" name="vip">
          <el-form label-width="120px">
            <el-form-item label="会员折扣">
              <el-input-number v-model="strategy.vipDiscount" :min="0" :max="100" :precision="1" style="width: 200px">
                <template #append>折</template>
              </el-input-number>
            </el-form-item>

            <el-divider>会员等级价格</el-divider>
            <el-table :data="strategy.vipLevels" stripe>
              <el-table-column prop="level" label="会员等级" />
              <el-table-column label="折扣">
                <template #default="{ row }">
                  <el-input-number v-model="row.discount" :min="0" :max="100" :precision="1" size="small">
                    <template #append>折</template>
                  </el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="阶梯定价" name="tier">
          <el-button type="primary" size="small" @click="handleAddTier">
            <el-icon><Plus /></el-icon>
            添加阶梯
          </el-button>
          <el-table :data="strategy.priceTiers" stripe style="margin-top: 15px">
            <el-table-column label="起订量">
              <template #default="{ row }">
                <el-input-number v-model="row.minQty" :min="1" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="单价">
              <template #default="{ row }">
                <el-input-number v-model="row.price" :min="0" :precision="2" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button type="danger" size="small" text @click="handleDeleteTier($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="strategyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveStrategy">保存策略</el-button>
      </template>
    </el-dialog>

    <!-- 价格历史对话框 -->
    <el-dialog v-model="historyDialogVisible" title="价格历史记录" width="800px">
      <el-table :data="priceHistory" stripe>
        <el-table-column prop="changeTime" label="变更时间" width="160" />
        <el-table-column prop="priceType" label="价格类型" width="100">
          <template #default="{ row }">
            <el-tag>{{ row.priceType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="oldPrice" label="原价格" width="100">
          <template #default="{ row }">
            ¥{{ row.oldPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="newPrice" label="新价格" width="100">
          <template #default="{ row }">
            ¥{{ row.newPrice }}
          </template>
        </el-table-column>
        <el-table-column label="变化" width="120">
          <template #default="{ row }">
            <el-tag :type="row.change > 0 ? 'danger' : 'success'">
              {{ row.change > 0 ? '+' : '' }}{{ row.change }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="变更原因" min-width="150" />
        <el-table-column prop="operator" label="操作人" width="100" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Money, Edit, Setting, Search, Right, Plus } from '@element-plus/icons-vue'

const searchText = ref('')
const priceDialogVisible = ref(false)
const strategyDialogVisible = ref(false)
const historyDialogVisible = ref(false)
const strategyTab = ref('markup')
const selectedProducts = ref([])

const products = ref([
  {
    id: 1,
    code: 'P001',
    name: 'iPhone 15',
    category: '电子产品',
    purchasePrice: 5000,
    salePrice: 5999,
    profitMargin: 19.98,
    lastPriceChange: '2024-10-01 10:00'
  },
  {
    id: 2,
    code: 'P002',
    name: 'MacBook Pro',
    category: '电子产品',
    purchasePrice: 12000,
    salePrice: 13999,
    profitMargin: 16.66,
    lastPriceChange: '2024-09-28 14:20'
  }
])

const currentProduct = ref({})

const priceForm = reactive({
  newPurchasePrice: 0,
  newSalePrice: 0,
  adjustType: 'fixed',
  adjustPercentage: 0,
  effectiveTime: '',
  reason: '',
  remark: ''
})

const strategy = reactive({
  defaultMarkup: 20,
  categoryMarkups: [
    { category: '电子产品', markup: 20 },
    { category: '服装鞋帽', markup: 50 },
    { category: '家居用品', markup: 30 }
  ],
  vipDiscount: 9.5,
  vipLevels: [
    { level: '普通会员', discount: 9.8 },
    { level: '银卡会员', discount: 9.5 },
    { level: '金卡会员', discount: 9 }
  ],
  priceTiers: [
    { minQty: 1, price: 100 },
    { minQty: 10, price: 95 },
    { minQty: 100, price: 90 }
  ]
})

const priceRecords = ref([
  {
    id: 1,
    productName: 'iPhone 15',
    type: '涨价',
    oldPrice: 4999,
    newPrice: 5999,
    reason: '成本上涨',
    time: '2024-10-01 10:00'
  },
  {
    id: 2,
    productName: 'MacBook Pro',
    type: '降价',
    oldPrice: 14999,
    newPrice: 13999,
    reason: '促销活动',
    time: '2024-09-28 14:20'
  }
])

const priceHistory = ref([
  {
    changeTime: '2024-10-01 10:00',
    priceType: '销售价',
    oldPrice: 4999,
    newPrice: 5999,
    change: 20,
    reason: '成本上涨',
    operator: '张三'
  }
])

const filteredProducts = computed(() => {
  if (!searchText.value) return products.value
  return products.value.filter(p => 
    p.name.includes(searchText.value) || 
    p.code.includes(searchText.value)
  )
})

const priceChangeInfo = computed(() => {
  if (!priceForm.newSalePrice || !priceForm.newPurchasePrice) return ''
  const oldMargin = ((currentProduct.value.salePrice - currentProduct.value.purchasePrice) / currentProduct.value.purchasePrice * 100).toFixed(2)
  const newMargin = ((priceForm.newSalePrice - priceForm.newPurchasePrice) / priceForm.newPurchasePrice * 100).toFixed(2)
  return `调价后毛利率将从 ${oldMargin}% 变为 ${newMargin}%`
})

const getProfitType = (profit) => {
  if (profit >= 30) return 'success'
  if (profit >= 20) return 'warning'
  return 'danger'
}

const handleSelectionChange = (selection) => {
  selectedProducts.value = selection
}

const handleAdjustPrice = (row) => {
  currentProduct.value = { ...row }
  priceForm.newPurchasePrice = row.purchasePrice
  priceForm.newSalePrice = row.salePrice
  priceDialogVisible.value = true
}

const handlePriceHistory = (row) => {
  historyDialogVisible.value = true
}

const applyPercentage = () => {
  const rate = 1 + priceForm.adjustPercentage / 100
  priceForm.newPurchasePrice = parseFloat((currentProduct.value.purchasePrice * rate).toFixed(2))
  priceForm.newSalePrice = parseFloat((currentProduct.value.salePrice * rate).toFixed(2))
}

const handleSubmitPrice = () => {
  ElMessage.success('调价成功')
  priceDialogVisible.value = false
}

const handleBatchPricing = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请先选择商品')
    return
  }
  ElMessage.info('批量调价功能开发中')
}

const handlePricingStrategy = () => {
  strategyDialogVisible.value = true
}

const handleAddTier = () => {
  strategy.priceTiers.push({ minQty: 1, price: 0 })
}

const handleDeleteTier = (index) => {
  strategy.priceTiers.splice(index, 1)
}

const handleSaveStrategy = () => {
  ElMessage.success('定价策略保存成功')
  strategyDialogVisible.value = false
}
</script>

<style scoped>
.pricing-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.page-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-cell {
  font-weight: 600;
  color: #f56c6c;
}

.record-content {
  padding-left: 10px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.record-detail {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 8px 0;
  font-size: 14px;
}

.old-price {
  text-decoration: line-through;
  color: #909399;
}

.new-price {
  color: #f56c6c;
  font-weight: 600;
}

.record-reason {
  font-size: 12px;
  color: #606266;
}
</style>

